<!-- 填写表单 -->
<template>
  <div
    class="writeForm"
    element-loading-text="表单加载中"
    element-loading-spinner="el-icon-loading"
    v-loading="loading"
  >
    <base-info
      ref="baseInfo"
      :base-info-data="baseInfo"
      :create-form="createForm"
      :isPCurl="isPCurl"
      :isPreview="isPreview"
      :isDetail="isDetail"
      :PCurlGetData="PCurlGetData"
    ></base-info>
    <div class="formRender">
      <ele-form
        ref="eleForm"
        :disabled="isDetail || isPCurl"
        labelPosition="right"
        :isResponsive="true"
        :inline="true"
        :formDesc="formDesc"
        :isShowSubmitBtn="false"
        :isShowErrorNotify="false"
        :isShowBackBtn="false"
        v-model="formData"
        labelWidth="120"
        @update:visible="$emit('change', $event)"
        :request-fn="handleRequest"
        @request-success="handleRequestSuccess"
      ></ele-form>
    </div>
  </div>
</template>

<script>
import BaseInfo from '../../components/BaseInfo.vue'
import formCenterApi from '@/api/formCenter'
import formDataApi from '@/api/formData'
import { extractFormDesc, formatParams, reFormatParams } from '../../utils/util'
import { getCodeFromName, getOrgFromCode } from '../../utils/index'
import { findNodePath } from '@/views/menuList/menus'
import { mapState } from 'vuex'
import eleForm from 'vue-ele-form'
export default {
  components: { BaseInfo, eleForm },
  data() {
    return {
      loading: true,
      baseInfo: {
        tip: '',
        tipFile: [],
        org: '',
        time: '',
        contact: '',
        phone: '',
        email: '',
        title: '',
        attachment: []
      },
      createForm: {
        name: '',
        menu: [],
        remark: ''
      },
      formDesc: {},
      formData: {},
      fieldList: {},
      isExpanded: false,
      type: 2 // 表单类型
    }
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    recordId: {
      type: String,
      default: undefined
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    isPreview: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: () => {}
    },
    updateTime: {
      type: String,
      default: ''
    },
    isPCurl: {
      type: Boolean,
      default: false
    },
    // 填完表的审批需要获取数据
    PCurlGetData: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(['loginData', 'orgList', 'menuList'])
  },
  methods: {
    async saveForm() {
      // 填后端的坑，先去查/lc/form/getById的fieldList，转成后端的id再提交
      const formData = formatParams(this.fieldList, this.formData)
      const params = { formId: this.id, recordId: this.recordId || '', data: { ...formData, ...this.baseInfo } }
      // 单独转换单位
      params.data.org = getCodeFromName(this.orgList, this.loginData.orgName)
      // const baseInfoRef = this.$refs.baseInfo.$refs.baseInfoForm
      // const valid = await baseInfoRef.validate()
      formDataApi.dataSaveOrUpdate(params).then(res => {
        if (res.data.code === 200) {
          this.$Message.success({
            content: '保存成功',
            duration: 2
          })
          this.$emit('Close', true)
        }
      })
    },
    async submit() {
      try {
        const baseInfoFormRef = this.$refs.baseInfo?.$refs.baseInfoForm
        if (!baseInfoFormRef) {
          this.$Message.error('基础信息表单引用无效')
          return
        }
        const formattedData = formatParams(this.fieldList, this.formData)
        const host = location.host
        const customHost = host.includes('sit') ? 'crinfo-uat.test.crcloud.com' : host
        const pcUrl = `https://${customHost}/form.html?type=formData&formType=${this.type}&id=${this.id}&recordId=`

        const orgCode = getCodeFromName(this.orgList, this.loginData?.orgName)
        if (!orgCode) {
          this.$Message.error('无法获取组织')
          // return
        }

        const params = {
          formId: this.id,
          recordId: this.recordId || '',
          pcUrl,
          data: { ...formattedData, ...this.baseInfo, org: orgCode }
        }

        await this.$confirm({ content: '是否确认提交?' })
        await this.$refs.eleForm.validate()
        const baseInfoValid = await baseInfoFormRef.validate()

        if (!baseInfoValid) {
          this.$Message.error('请检查表单必填项')
          return
        }
        const res = await formDataApi.dataSubmit(params)
        if (res.data.code === 200) {
          this.$Message.success({ content: '提交成功', duration: 2 })
          this.$emit('Close', true)
        } else {
          this.$Message.error('提交失败: ' + res.data.message || '未知错误')
        }
      } catch (error) {
        console.error('提交过程中发生错误:', error)
        this.$Message.error('请检查表单必填项')
      }
    },
    setBaseInfoFromLogin(userData) {
      const now = new Date()
      const formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now
        .getDate()
        .toString()
        .padStart(2, '0')}`
      this.baseInfo.org = userData?.orgName || '-'
      this.baseInfo.time = this.updateTime.split(' ')[0] || formattedDate
      this.baseInfo.contact = userData.userName
      this.baseInfo.phone = userData.mobile
      this.baseInfo.email = userData.email
    },
    setBaseInfoFromRowData(rowData) {
      let orgName = getOrgFromCode(this.orgList, rowData.org)
      if (orgName) {
        this.baseInfo.org = orgName
      } else {
        console.error('没有找到对应的组织信息')
        this.baseInfo.org = '-'
      }
      this.baseInfo.time = rowData.createTime.split(' ')[0]
      this.baseInfo.contact = rowData.contact || '-'
      this.baseInfo.phone = rowData.phone || '-'
      this.baseInfo.email = rowData.email || '-'
    },
    handlePCFormData(res, PCurlGetData) {
      const config = JSON.parse(res.config)
      this.formDesc = extractFormDesc({ treeData: config.treeData, isFn: false, isDetail: PCurlGetData })
      // this.baseInfo = { ...this.baseInfo, ...config.baseInfo } // 合并对象，以防有额外属性
      this.baseInfo.tip = config.baseInfo.tip
      this.baseInfo.tipFile = config.baseInfo.tipFile
      // this.name = res.name
      // this.remark = res.remark
      // 表单信息
      this.createForm.name = res.name
      this.createForm.remark = res.remark
      this.createForm.menu = findNodePath(this.menuList, res.menu)
    },
    handlePreviewData() {
      this.formDesc = extractFormDesc({ treeData: this.row.treeData, isFn: false, disabledColumn: true }) // 预览附件按钮不让上传
      this.baseInfo = this.row.baseInfo
      // this.name = this.row.name
      // this.remark = this.row.remark
      this.setBaseInfoFromLogin(this.loginData)
    },
    setPageActions() {
      const btnList = [
        {
          text: '取消',
          handle: () => {
            this.$emit('Close')
          }
        },
        {
          text: '保存',
          handle: this.saveForm
        },
        {
          text: '提交',
          theme: 'primary',
          handle: this.submit
        }
      ]
      this.$emit('SetPageActions', this.isDetail ? [] : btnList)
    },
    async getDynamicFormConfig(id) {
      // 动态获取表单配置，根据不同的条件获取不同的数据
      const res = await formCenterApi.getFormPage({ id })
      const row = res.data.data.records[0]
      // this.name = row.name
      this.type = row.type
      // this.remark = row.remark
      if (row.config) {
        const config = JSON.parse(row.config)
        this.baseInfo.tip = config.baseInfo.tip
        this.baseInfo.tipFile = config.baseInfo.tipFile
        this.formDesc = extractFormDesc({
          treeData: config.treeData,
          isFn: true,
          isDetail: this.isDetail,
          disabledColumn: true
        })
      }
    },
    handleRecordData(res) {
      // 动态表格数据的处理逻辑
      // 转换后端key--动态表格数据的key都是‘fld’开头
      const formData = Object.entries(res.data).reduce((acc, [key, value]) => {
        if (key.startsWith('fld')) {
          acc[key] = value
        }
        return acc
      }, {})
      this.formData = reFormatParams(this.fieldList, formData)
      if (this.isDetail) {
        this.setBaseInfoFromRowData(res.data)
      }
      this.baseInfo.attachment = res.data.attachment || []
      this.baseInfo.title = res.data.title
      this.loading = false
    },
    async handleApprovalData(res) {
      const setBaseInfo = baseInfo => {
        // 前端需要转换单位名称
        let orgName = getOrgFromCode(this.orgList, baseInfo.org)
        if (orgName) {
          this.baseInfo.org = orgName
        } else {
          console.error('没有找到对应的组织信息')
          this.baseInfo.org = '-'
        }
        this.baseInfo.time = baseInfo.createTime.split(' ')[0]
        this.baseInfo.contact = baseInfo.contact || '-'
        this.baseInfo.phone = baseInfo.phone || '-'
        this.baseInfo.email = baseInfo.email || '-'
        this.baseInfo.title = baseInfo.title
        this.baseInfo.attachment = baseInfo.attachment
      }
      // 动态表格数据的处理逻辑
      // 转换后端key--动态表格数据的key都是‘fld’开头
      const formData = Object.entries(res.data).reduce((acc, [key, value]) => {
        if (key.startsWith('fld')) {
          acc[key] = value
        }
        return acc
      }, {})
      const result = await formCenterApi.formGetById({ id: this.id })
      const fieldList = result.fieldList
      this.formData = reFormatParams(fieldList, formData)
      setBaseInfo(res.data)
    },
    handleRequest() {},
    handleRequestSuccess() {}
  },

  async created() {
    try {
      // 炎黄嵌入需要在这里调用组织接口
      if (this.orgList.length <= 0) {
        await this.$store.dispatch('getOrgList')
      }
      // 根据不同条件获取表单数据
      if (this.isPCurl) {
        // 炎黄页面
        // 获取表单配置
        if (!this.PCurlGetData) {
          // 制表审核获取菜单
          await this.$store.dispatch('getMenuList')
        }
        const pcFormData = await formCenterApi.formGetById({ id: this.id })
        // 这里需要判断是制表的审批还是填完表的审批，填完表的审批需要将附件上传转为a标签，图片
        this.handlePCFormData(pcFormData, this.PCurlGetData)
        if (this.PCurlGetData) {
          // 填完表审批，获取表单数据
          const recordData = await formDataApi.dataGetById({ formId: this.id, recordId: this.recordId })
          this.handleApprovalData(recordData)
        }
      } else if (this.isPreview) {
        // 预览模式下
        this.handlePreviewData()
      } else {
        // 填表编辑与详情
        const formData = await formCenterApi.formGetById({ id: this.id })
        this.fieldList = formData.fieldList
        if (Object.keys(this.loginData).length === 0) {
          await this.$store.dispatch('getLoginData')
        }
        this.setBaseInfoFromLogin(this.loginData)
        this.setPageActions()
        // 获取动态表单配置
        await this.getDynamicFormConfig(this.id)

        // 获取动态表格数据
        if (this.isEdit || this.isDetail) {
          const recordData = await formDataApi.dataGetById({ formId: this.id, recordId: this.recordId })
          this.handleRecordData(recordData)
        }
      }
      this.loading = false
    } catch (error) {
      console.error('An error occurred in the created hook:', error)
    }
  }
}
</script>

<style lang="less" scoped>
.writeForm {
  padding-left: 20px;
  padding-right: 20px;
  height: 98%;

  // 给input-number添加百分号
  /deep/.el-form .my-input-number {
    position: relative;
    &::after {
      content: '%';
      display: inline-block;
      height: 20px;
      line-height: 20px;
      width: 20px;
      text-align: center;
      position: absolute;
      right: 25%;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  /deep/.el-radio-group {
    display: flex;
    flex-wrap: wrap;
    .el-radio {
      height: auto;
      width: 110px;
      padding: 12px 0;
      .el-radio__label {
        overflow-wrap: break-word;
        white-space: normal;
      }
    }
  }
  /deep/.el-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    // margin-top: 14px;
    .el-checkbox {
      // display: flex;
      // padding: 5px 0;
      height: auto;
      width: 110px;
      .el-checkbox__label {
        word-break: break-all;
        white-space: normal;
      }
    }
  }
}
</style>
